package com.ksyun.campus.metaserver.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;

/**
 * 切换redis操作
 */
@Slf4j
@Configuration
public class RedisSwitchManager {
    public static final Integer MASTER_REDIS_DATABASE = 1;
    public static final Integer SLAVE_REDIS_DATABASE = 2;
    @Resource
    private LettuceConnectionFactory redisConnectionFactory;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private GenericApplicationContext context;

    public void switchToMaster() {
        if (getDatabaseIndex() == SLAVE_REDIS_DATABASE) {
            log.info("切换当前节点redis数据库为1号主节点数据库");
            switchDatabase(MASTER_REDIS_DATABASE);
        } else {
            log.info("redis数据库编号为1，无需更改");
        }
    }

    public void switchToSlave() {
        if (getDatabaseIndex() == MASTER_REDIS_DATABASE) {
            log.info("切换当前节点redis数据库为2号主节点数据库");
            switchDatabase(SLAVE_REDIS_DATABASE);
        } else {
            log.info("redis数据库编号为2，无需更改");
        }
    }

    /**
     * 将当前节点的redis数据库切换成databaseIndex
     * @param databaseIndex 编号
     */
    private void switchDatabase(int databaseIndex) {
        try {
            redisConnectionFactory.setDatabase(databaseIndex);
            // 刷新配置
            redisConnectionFactory.afterPropertiesSet();
            // 重置连接以应用新配置
            redisConnectionFactory.resetConnection();
        } catch (Exception e) {
            throw new RuntimeException("切换redis database异常", e);
        }
    }

    /**
     * 获取当前节点的redis连接的数据库
     * @return 编号
     */
    private int getDatabaseIndex() {
        try {
            LettuceConnectionFactory connectionFactory = redisConnectionFactory;
            return connectionFactory.getDatabase();
        } catch (Exception e) {
            throw new RuntimeException("获取当前节点的redis database编号异常", e);
        }
    }
}
